<style lang="scss">
* {
  margin: 0;
  padding: 0;
}

li {
  list-style: none;
}

html,
body {
  width: 100%;
  height: 100%;
  margin: 0; // 清除默认边距
  background-color: #161622;
  padding-top: env(safe-area-inset-top);
  padding-bottom: env(safe-area-inset-bottom);
  height: calc(var(--vh) - env(safe-area-inset-top) - env(safe-area-inset-bottom)) !important;
}

ul,
ol {
  list-style: none;
}

#app {
  width: 100%;
  height: 100%;
}

.container {
  width: 100%;
  height: 100%;
}

.fullscreen-tip {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #fff;
  font-size: 0.3733rem;
  background: rgba(0, 0, 0, 0.5);
  padding: 0.2rem 0.4rem;
  border-radius: 0.2rem;
  z-index: 9999;
  /* 确保在最上层 */
  pointer-events: none;
  /* 不影响下层点击 */
}
</style>
<template>
  <div class="container">
    <BaseLoading v-if="loadingStore.isLoading" />
    <router-view></router-view>
    <TabBar v-if="shouldShowTabBar"></TabBar>
    <LoginModal></LoginModal>
    <RegisterModal></RegisterModal>
    <ForgotPasswordModal></ForgotPasswordModal>
    <!-- <div class="fullscreen-tip" v-if="!isFullScreen && userStore.isLogin">
      点击任意位置进入全屏
    </div> -->
    <AppSuspense />
  </div>
</template>
<script setup>
import { useRoute } from 'vue-router';
import TabBar from './components/common/TabBar.vue';
import LoginModal from './components/login/LoginModal.vue';
import RegisterModal from './components/login/RegisterModal.vue';
import ForgotPasswordModal from './components/login/ForgotPasswordModal.vue';
import { useUserStore } from '@/store/modules/user/user.js'
import { useMessageStore } from '@/store/modules/message/message.js'
import { useFullScreen } from '@/hooks/useFullScreen.js'
import AppSuspense from './components/loading/AppSuspense .vue'
import BaseLoading from './components/loading/BaseLoading copy.vue'
import { useLoadingStore } from './store/modules/loading.js';
import { fetchFanUnreadNum, fetchLikeUnreadNum, fetchCommentUnreadNum, fetchAtUnreadNum, fetchAllMessageUnreadNums } from './hooks/fetchAllMessageUnreadNums'
import { computed } from 'vue';
const socket = inject('socket')
const messageStore = useMessageStore()
const userStore = useUserStore()
const { isFullScreen, requestFullScreen } = useFullScreen()
// // 获取当前路由
const route = useRoute();
const loadingStore = useLoadingStore()

const excludePaths = [
  '/video',
  '/user/fans',
  '/user/follows',
  '/message/followers',
  '/message/likes',
  '/message/mentions',
  '/message/comments',
  '/search',
  '/contact-picker',
  'ChatWith',
];

// 2. 计算属性：判断当前路径是否需要显示TabBar
const shouldShowTabBar = computed(() => {
  // 当前路径是否不在排除列表中（即需要显示TabBar）
  return !excludePaths.some(path => route.path.includes(path));
});
async function handleLoginSuccess(userId) {
  try {
    const res = await fetchAllMessageUnreadNums(userId);
    messageStore.unreadMessages = {
      ...messageStore.unreadMessages,
      ...res
    };
    console.log('登录时初始化未读数量：', messageStore.unreadMessages);
  } catch (err) {
    console.error('初始化未读数量失败：', err);
  }
}
watch(
  () => userStore.isLogin,
  async (isLogin) => {
    if (isLogin && userStore.userInfo?.userId) {
      if (socket.connected) {
        // 已连接：直接发送登录
        await handleLoginSuccess(userStore.userInfo.userId)
        socket.emit('login', userStore.userInfo.userId);
      } else {
        // 未连接：监听connect事件后再发送登录
        await handleLoginSuccess(userStore.userInfo.userId)
        socket.connect();
        socket.once('connect', () => { // once确保只执行一次
          socket.emit('login', userStore.userInfo.userId);
        });
      }
    }
  },
  { immediate: true }
)
onMounted(() => {
  // 监听服务器发送的私信消息
  socket.on('receivePrivateLetter', (msg) => {
    console.log('收到私信消息:', msg);
    messageStore.addChatMessage(msg)
    console.log('私信消息后未读消息数量:', messageStore.newMessageNum);
  })
  // 监听服务器发送的评论消息
  socket.on('receiveComment', (msg) => {
    console.log('收到评论消息:', msg);
    fetchCommentUnreadNum(userStore.userInfo.userId).then(res => {
      messageStore.addCommentMessage(res)
    })
  })
  // 监听服务器发送的点赞消息
  socket.on('receiveTriggerLike', (msg) => {
    console.log('收到点赞消息:', msg);
    // 刷新未读消息数
    fetchLikeUnreadNum(userStore.userInfo.userId).then(res => {
      messageStore.addLikeMessage(res)
    })
  })
  // 监听服务器发送的关注消息
  socket.on('receiveTriggerFollow', (msg) => {
    console.log('收到关注消息:', msg);
    fetchFanUnreadNum(userStore.userInfo.userId).then(res => {
      messageStore.addFanMessage(res)
    })
  })
})
const handleFirstInteraction = () => {
  requestFullScreen();
  // 移除监听，避免重复触发
  document.documentElement.removeEventListener('touchstart', handleFirstInteraction);
  document.documentElement.removeEventListener('click', handleFirstInteraction);
};



// 3. 组件卸载时，移除所有事件监听
onUnmounted(() => {
  socket.off('receiveComment')
  socket.off('receiveTriggerLike')
  socket.off('receiveTriggerFollow')
  socket.off('receivePrivateLetter')
})
</script>